import 'package:flutter/material.dart';
import '../../models/user_model.dart';

class SkillManagementPage extends StatefulWidget {
  const SkillManagementPage({super.key});

  @override
  State<SkillManagementPage> createState() => _SkillManagementPageState();
}

class _SkillManagementPageState extends State<SkillManagementPage> {
  // 模拟用户技能数据
  final List<SkillTag> _skills = [
    SkillTag(
      id: '1',
      name: 'React',
      category: '技术',
      level: SkillLevel.advanced,
      isCertified: true,
      createdAt: DateTime.now(),
    ),
    SkillTag(
      id: '2',
      name: 'Flutter',
      category: '技术',
      level: SkillLevel.intermediate,
      isCertified: false,
      createdAt: DateTime.now(),
    ),
    SkillTag(
      id: '3',
      name: 'Vue.js',
      category: '技术',
      level: SkillLevel.advanced,
      isCertified: true,
      createdAt: DateTime.now(),
    ),
    SkillTag(
      id: '4',
      name: 'UI设计',
      category: '设计',
      level: SkillLevel.beginner,
      isCertified: false,
      createdAt: DateTime.now(),
    ),
  ];

  // 技能点击统计
  final Map<String, int> _skillClickCounts = {
    '1': 156, // React
    '2': 89, // Flutter
    '3': 234, // Vue.js
    '4': 45, // UI设计
  };

  final List<String> _skillCategories = ['技术', '设计', '产品', '运营', '其他'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('技能标签管理'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => _showAddSkillDialog(),
          ),
        ],
      ),
      body: Column(
        children: [
          // 统计卡片
          Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Theme.of(context).primaryColor,
                  Theme.of(context).primaryColor.withOpacity(0.8),
                ],
              ),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem(
                    '技能总数', _skills.length.toString(), Icons.psychology),
                _buildStatItem(
                    '认证技能',
                    _skills.where((s) => s.isCertified).length.toString(),
                    Icons.verified),
                _buildStatItem(
                    '总点击量',
                    _skillClickCounts.values
                        .fold(0, (sum, count) => sum + count)
                        .toString(),
                    Icons.touch_app),
              ],
            ),
          ),
          // 技能列表
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              itemCount: _skills.length,
              itemBuilder: (context, index) {
                final skill = _skills[index];
                final clickCount = _skillClickCounts[skill.id] ?? 0;

                return Card(
                  margin: const EdgeInsets.only(bottom: 8),
                  child: ListTile(
                    leading: Container(
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color:
                            _getSkillLevelColor(skill.level).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Icon(
                        Icons.psychology,
                        color: _getSkillLevelColor(skill.level),
                        size: 24,
                      ),
                    ),
                    title: Row(
                      children: [
                        Text(
                          skill.name,
                          style: const TextStyle(fontWeight: FontWeight.w500),
                        ),
                        if (skill.isCertified)
                          const Padding(
                            padding: EdgeInsets.only(left: 8),
                            child: Icon(
                              Icons.verified,
                              color: Colors.amber,
                              size: 16,
                            ),
                          ),
                      ],
                    ),
                    subtitle: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('分类：${skill.category}'),
                        Text('等级：${_getSkillLevelText(skill.level)}'),
                        Text('点击次数：$clickCount'),
                      ],
                    ),
                    trailing: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.edit, size: 20),
                          onPressed: () => _showEditSkillDialog(skill),
                        ),
                        IconButton(
                          icon: const Icon(Icons.delete,
                              size: 20, color: Colors.red),
                          onPressed: () => _showDeleteSkillDialog(skill),
                        ),
                      ],
                    ),
                    onTap: () => _incrementSkillClick(skill.id),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(icon, color: Colors.white, size: 24),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          label,
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  void _showAddSkillDialog() {
    final TextEditingController nameController = TextEditingController();
    String selectedCategory = _skillCategories.first;
    SkillLevel selectedLevel = SkillLevel.beginner;
    bool isCertified = false;

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('添加技能'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '技能名称',
                  hintText: '请输入技能名称',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),
              DropdownButtonFormField<String>(
                value: selectedCategory,
                decoration: const InputDecoration(
                  labelText: '技能分类',
                  border: OutlineInputBorder(),
                ),
                items: _skillCategories
                    .map((category) => DropdownMenuItem(
                          value: category,
                          child: Text(category),
                        ))
                    .toList(),
                onChanged: (value) {
                  setState(() {
                    selectedCategory = value!;
                  });
                },
              ),
              const SizedBox(height: 16),
              DropdownButtonFormField<SkillLevel>(
                value: selectedLevel,
                decoration: const InputDecoration(
                  labelText: '技能等级',
                  border: OutlineInputBorder(),
                ),
                items: SkillLevel.values
                    .map((level) => DropdownMenuItem(
                          value: level,
                          child: Text(_getSkillLevelText(level)),
                        ))
                    .toList(),
                onChanged: (value) {
                  setState(() {
                    selectedLevel = value!;
                  });
                },
              ),
              const SizedBox(height: 16),
              CheckboxListTile(
                title: const Text('已认证'),
                value: isCertified,
                onChanged: (value) {
                  setState(() {
                    isCertified = value ?? false;
                  });
                },
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                if (nameController.text.trim().isNotEmpty) {
                  final newSkill = SkillTag(
                    id: DateTime.now().millisecondsSinceEpoch.toString(),
                    name: nameController.text.trim(),
                    category: selectedCategory,
                    level: selectedLevel,
                    isCertified: isCertified,
                    createdAt: DateTime.now(),
                  );
                  setState(() {
                    _skills.add(newSkill);
                    _skillClickCounts[newSkill.id] = 0;
                  });
                  Navigator.pop(context);
                  _showSuccessMessage('技能添加成功');
                }
              },
              child: const Text('添加'),
            ),
          ],
        ),
      ),
    );
  }

  void _showEditSkillDialog(SkillTag skill) {
    final TextEditingController nameController =
        TextEditingController(text: skill.name);
    String selectedCategory = skill.category;
    SkillLevel selectedLevel = skill.level;
    bool isCertified = skill.isCertified;

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('编辑技能'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '技能名称',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),
              DropdownButtonFormField<String>(
                value: selectedCategory,
                decoration: const InputDecoration(
                  labelText: '技能分类',
                  border: OutlineInputBorder(),
                ),
                items: _skillCategories
                    .map((category) => DropdownMenuItem(
                          value: category,
                          child: Text(category),
                        ))
                    .toList(),
                onChanged: (value) {
                  setState(() {
                    selectedCategory = value!;
                  });
                },
              ),
              const SizedBox(height: 16),
              DropdownButtonFormField<SkillLevel>(
                value: selectedLevel,
                decoration: const InputDecoration(
                  labelText: '技能等级',
                  border: OutlineInputBorder(),
                ),
                items: SkillLevel.values
                    .map((level) => DropdownMenuItem(
                          value: level,
                          child: Text(_getSkillLevelText(level)),
                        ))
                    .toList(),
                onChanged: (value) {
                  setState(() {
                    selectedLevel = value!;
                  });
                },
              ),
              const SizedBox(height: 16),
              CheckboxListTile(
                title: const Text('已认证'),
                value: isCertified,
                onChanged: (value) {
                  setState(() {
                    isCertified = value ?? false;
                  });
                },
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                if (nameController.text.trim().isNotEmpty) {
                  final updatedSkill = SkillTag(
                    id: skill.id,
                    name: nameController.text.trim(),
                    category: selectedCategory,
                    level: selectedLevel,
                    isCertified: isCertified,
                    createdAt: skill.createdAt,
                  );
                  setState(() {
                    final index = _skills.indexWhere((s) => s.id == skill.id);
                    if (index != -1) {
                      _skills[index] = updatedSkill;
                    }
                  });
                  Navigator.pop(context);
                  _showSuccessMessage('技能更新成功');
                }
              },
              child: const Text('保存'),
            ),
          ],
        ),
      ),
    );
  }

  void _showDeleteSkillDialog(SkillTag skill) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除技能'),
        content: Text('确定要删除技能"${skill.name}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                _skills.removeWhere((s) => s.id == skill.id);
                _skillClickCounts.remove(skill.id);
              });
              Navigator.pop(context);
              _showSuccessMessage('技能删除成功');
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  void _incrementSkillClick(String skillId) {
    setState(() {
      _skillClickCounts[skillId] = (_skillClickCounts[skillId] ?? 0) + 1;
    });
    _showSuccessMessage('技能点击已记录');
  }

  Color _getSkillLevelColor(SkillLevel level) {
    switch (level) {
      case SkillLevel.beginner:
        return Colors.green;
      case SkillLevel.intermediate:
        return Colors.orange;
      case SkillLevel.advanced:
        return Colors.red;
      case SkillLevel.expert:
        return Colors.purple;
    }
  }

  String _getSkillLevelText(SkillLevel level) {
    switch (level) {
      case SkillLevel.beginner:
        return '初级';
      case SkillLevel.intermediate:
        return '中级';
      case SkillLevel.advanced:
        return '高级';
      case SkillLevel.expert:
        return '专家';
    }
  }

  void _showSuccessMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }
}
